import { createStore } from 'vuex';
import { AuthService, UserService, MembershipService, StatsService } from '../services';

// 模拟用户数据，实际应用中应该从后端API获取
const mockUsers = [
  {
    id: 1,
    username: 'test',
    password: 'test123', // 实际应用中应该加密
    email: 'test@example.com',
    isPro: false,
    registerDate: '2023-01-01',
    proExpiryDate: null
  },
  {
    id: 2,
    username: 'admin',
    password: 'admin123',
    email: 'admin@example.com',
    isPro: true,
    registerDate: '2023-01-01',
    proExpiryDate: '2024-01-01'
  }
];

// 免费功能列表
const freeFunctions = [
  'capitalization', // 首字母大写
  'upperCase', // 大写转换
  'lowerCase', // 小写转换
  'sentenceCase', // 句首大写
  'reverseText', // 文本反转
  'removeLineBreaks', // 移除换行
  'countCharacters', // 字符统计
  'convertPunctuation', // 标点符号转换
  'img-compress-basic', // 基础图片压缩
  'img-compress-jpg-png', // JPG/PNG格式支持
];

// 付费功能列表
const proFunctions = [
  'removeExtraSpaces', // 移除多余空格
  'convertChineseNums', // 中文数字转换
  'markdown', // Markdown转纯文本
  'ocr', // OCR识别
  'pdf-advanced', // PDF高级操作
  'ai-generator', // AI辅助生成
  'advanced-format', // 高级格式转换
  'img-compress-pro', // 高级图片压缩
  'img-compress-webp', // WebP格式支持
  'img-compress-lossless', // 无损压缩
  'img-compress-batch', // 批量压缩
  'img-compress-watermark', // 自定义水印
];

const store = createStore({
  state() {
    return {
      user: null,
      isLoggedIn: false,
      freeFunctions,
      proFunctions,
      usageHistory: [], // 记录功能使用历史
      latestTools: [], // 最近使用的工具
      toolUsageStats: {
        text: {},
        image: {},
        converters: {},
        efficiency: {},
        data: {},
        design: {}
      },
      pageViews: {},
    };
  },
  getters: {
    // 用户是否为Pro会员
    isPro(state) {
      if (!state.isLoggedIn || !state.user) return false;
      return state.user.isPro;
    },
    
    // 检查功能是否可用
    canUseFunction: (state, getters) => (functionId) => {
      // 检查是否为免费功能
      if (state.freeFunctions.includes(functionId)) {
        return true;
      }
      
      // 如果是付费功能，检查用户是否是Pro会员
      if (state.proFunctions.includes(functionId)) {
        return getters.isPro;
      }
      
      return false;
    },
    
    // 获取功能使用历史
    getUsageHistory(state) {
      return state.usageHistory;
    },
    
    // 获取用户个人信息
    userInfo(state) {
      return state.user;
    },
    currentUser: state => state.user,
    isLoggedIn: state => state.isLoggedIn,
    getToolUsage: (state) => (category, tool) => {
      if (state.toolUsageStats[category] && state.toolUsageStats[category][tool]) {
        return state.toolUsageStats[category][tool];
      }
      return 0;
    },
    getMostUsedTools: (state) => (category, limit = 5) => {
      if (!state.toolUsageStats[category]) return [];
      
      const tools = Object.keys(state.toolUsageStats[category]).map(tool => ({
        tool,
        count: state.toolUsageStats[category][tool]
      }));
      
      return tools.sort((a, b) => b.count - a.count).slice(0, limit);
    },
    getPageViews: (state) => (page) => {
      return state.pageViews[page] || 0;
    }
  },
  mutations: {
    // 登录成功
    loginSuccess(state, user) {
      state.user = user;
      state.isLoggedIn = true;
    },
    
    // 注销
    logout(state) {
      state.user = null;
      state.isLoggedIn = false;
    },
    
    // 记录功能使用
    recordFunctionUsage(state, { functionName, isPro }) {
      // 添加使用记录
      state.usageHistory.push({
        functionName,
        isPro,
        date: new Date().toISOString()
      });
      
      // 限制历史记录最大数量
      if (state.usageHistory.length > 50) {
        state.usageHistory.shift();
      }
      
      // 更新最近使用的工具
      const toolIndex = state.latestTools.findIndex(tool => tool.name === functionName);
      if (toolIndex > -1) {
        state.latestTools.splice(toolIndex, 1);
      }
      
      state.latestTools.unshift({
        name: functionName,
        isPro,
        date: new Date().toISOString()
      });
      
      if (state.latestTools.length > 5) {
        state.latestTools.pop();
      }
    },
    
    // 升级到Pro会员
    upgradeToPro(state, expiryDate) {
      if (state.user) {
        state.user.isPro = true;
        state.user.proExpiryDate = expiryDate;
      }
    },
    
    // 更新用户个人资料
    updateUserProfile(state, userInfo) {
      if (state.user) {
        state.user = { ...state.user, ...userInfo };
      }
    },
    setUser(state, user) {
      state.user = user;
      state.isLoggedIn = !!user;
    },
    incrementToolUsage(state, { category, tool }) {
      if (!state.toolUsageStats[category]) {
        state.toolUsageStats[category] = {};
      }
      
      if (!state.toolUsageStats[category][tool]) {
        state.toolUsageStats[category][tool] = 0;
      }
      
      state.toolUsageStats[category][tool]++;
    },
    addToolUsageLog(state, { category, tool, timestamp }) {
      if (!state.toolUsageStats[category]) {
        state.toolUsageStats[category] = {};
      }
      
      if (!state.toolUsageStats[category][tool]) {
        state.toolUsageStats[category][tool] = 0;
      }
      
      state.toolUsageStats[category][tool]++;
      
      // 如果用户已登录，可以发送到服务器存储
      if (state.isLoggedIn && state.user) {
        // 这里实际项目中应该有API调用来记录使用日志
        console.log('记录工具使用:', { 
          user: state.user.id, 
          category, 
          tool, 
          timestamp 
        });
      }
    },
    incrementPageView(state, { page }) {
      if (!state.pageViews[page]) {
        state.pageViews[page] = 0;
      }
      
      state.pageViews[page]++;
    }
  },
  actions: {
    // 登录
    login({ commit }, credentials) {
      return new Promise(async (resolve, reject) => {
        try {
          const response = await AuthService.login(credentials);
          
          // 检查并安全获取用户信息
          const responseData = response.data || {};
          const userInfo = responseData.user || {
            username: credentials.username,
            id: responseData.userId || 0,
            // 根据后端返回数据结构设置默认值
            email: responseData.email || '',
            role: responseData.role || 'user',
            isPro: responseData.isPro || false
          };
          
          commit('loginSuccess', userInfo);
          resolve(userInfo);
        } catch (error) {
          reject(error);
        }
      });
    },
    
    // 登出
    logout({ commit }) {
      return new Promise(async (resolve) => {
        AuthService.logout();
        commit('logout');
        resolve();
      });
    },
    
    // 刷新令牌
    refreshToken({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          if (AuthService.isTokenExpired()) {
            const response = await AuthService.refreshToken();
            resolve(response);
          } else {
            resolve({ message: '令牌未过期' });
          }
        } catch (error) {
          // 刷新令牌失败，登出用户
          commit('logout');
          reject(error);
        }
      });
    },
    
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          const response = await UserService.getUserProfile();
          const userInfo = response.data;
          commit('setUser', userInfo);
          resolve(userInfo);
        } catch (error) {
          reject(error);
        }
      });
    },
    
    // 更新用户信息
    updateUserProfile({ commit }, profileData) {
      return new Promise(async (resolve, reject) => {
        try {
          const response = await UserService.updateUserProfile(profileData);
          const userInfo = response.data;
          commit('updateUserProfile', userInfo);
          resolve(userInfo);
        } catch (error) {
          reject(error);
        }
      });
    },
    
    // 获取会员状态
    getMembershipStatus({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          const response = await MembershipService.getMembershipStatus();
          const membershipStatus = response.data;
          resolve(membershipStatus);
        } catch (error) {
          reject(error);
        }
      });
    },
    
    // 升级到Pro会员
    upgradeToPro({ commit }, upgradeData) {
      return new Promise(async (resolve, reject) => {
        try {
          const response = await MembershipService.upgradeMembership(upgradeData);
          const membershipStatus = response.data.membershipStatus;
          commit('upgradeToPro', membershipStatus.proExpiryDate);
          resolve(response.data);
        } catch (error) {
          reject(error);
        }
      });
    },
    
    // 记录工具使用
    recordToolUsage({ commit, state }, { category, tool, timestamp = new Date().toISOString() }) {
      commit('incrementToolUsage', { category, tool });
      
      // 记录到服务器
      if (state.isLoggedIn && state.user) {
        return StatsService.recordToolUsage({
          toolType: category,
          operationType: tool,
          metadata: {
            timestamp
          }
        }).catch(error => console.error('Failed to record tool usage:', error));
      }
    },
    
    // 用户注册
    register({ commit }, userData) {
      return new Promise((resolve, reject) => {
        // 模拟注册过程
        setTimeout(() => {
          // 检查用户名是否已存在
          const existingUser = mockUsers.find(u => u.username === userData.username);
          if (existingUser) {
            reject(new Error('用户名已存在'));
            return;
          }
          
          // 创建新用户
          const newUser = {
            id: mockUsers.length + 1,
            username: userData.username,
            password: userData.password,
            email: userData.email,
            isPro: false,
            registerDate: new Date().toISOString().split('T')[0],
            proExpiryDate: null
          };
          
          mockUsers.push(newUser);
          resolve(true);
        }, 500);
      });
    },
    
    // 使用功能
    useFunction({ commit, getters }, { functionId, isPro }) {
      // 检查功能是否可用
      if (isPro && !getters.isPro) {
        throw new Error('无法使用此功能，请升级到Pro会员');
      }
      
      // 记录功能使用
      commit('recordFunctionUsage', { functionName: functionId, isPro });
      
      return true;
    },
    
    // 获取会员状态
    getMembershipStatus({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          const response = await MembershipService.getMembershipStatus();
          const membershipStatus = response.data;
          resolve(membershipStatus);
        } catch (error) {
          reject(error);
        }
      });
    },
    incrementPageView({ commit }, { page, timestamp }) {
      commit('incrementPageView', { page });
      
      // 如果用户已登录，可以发送到服务器存储
      if (this.state.isLoggedIn && this.state.user) {
        // 这里实际项目中应该有API调用来记录页面访问
        console.log('记录页面访问:', { 
          user: this.state.user.id, 
          page, 
          timestamp 
        });
      }
    }
  },
  modules: {
    // ... 模块
  }
});

export default store; 